<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class ProductVariant extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'product_id',
        'sku',
        'name',
        'price',
        'compare_price',
        'cost_price',
        'stock_quantity',
        'low_stock_threshold',
        'weight',
        'length',
        'width',
        'height',
        'barcode',
        'attributes',
        'is_active',
        'is_default',
        'sort_order',
        'meta_data',
        'description',
        'features',
        'overrides_price',
        'overrides_stock',
        'overrides_weight',
        'overrides_dimensions',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'compare_price' => 'decimal:2',
        'cost_price' => 'decimal:2',
        'attributes' => 'array',
        'is_active' => 'boolean',
        'is_default' => 'boolean',
        'overrides_price' => 'boolean',
        'overrides_stock' => 'boolean',
        'overrides_weight' => 'boolean',
        'overrides_dimensions' => 'boolean',
        'meta_data' => 'array',
        'features' => 'array',
        'deleted_at' => 'datetime',
    ];

    /**
     * 产品关联
     */
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * 变体图片
     */
    public function images(): HasMany
    {
        return $this->hasMany(ProductVariantImage::class, 'variant_id');
    }

    /**
     * 变体属性值
     */
    public function attributeValues(): HasMany
    {
        return $this->hasMany(VariantAttributeValue::class, 'variant_id');
    }

    /**
     * 主图片
     */
    public function primaryImage()
    {
        return $this->images()->where('is_primary', true)->first();
    }

    /**
     * 检查是否有库存
     */
    public function inStock(): bool
    {
        return $this->stock_quantity > 0;
    }

    /**
     * 检查是否低库存
     */
    public function isLowStock(): bool
    {
        return $this->stock_quantity <= $this->low_stock_threshold;
    }

    /**
     * 获取折扣百分比
     */
    public function getDiscountPercentageAttribute(): ?float
    {
        if (!$this->compare_price || $this->compare_price <= $this->price) {
            return null;
        }
        
        return round((($this->compare_price - $this->price) / $this->compare_price) * 100, 2);
    }

    /**
     * 获取属性显示文本
     */
    public function getAttributeDisplayAttribute(): string
    {
        if (!$this->attributes) {
            return '';
        }
        
        $display = [];
        foreach ($this->attributes as $key => $value) {
            $display[] = ucfirst($key) . ': ' . $value;
        }
        
        return implode(', ', $display);
    }

    /**
     * 作用域：激活的变体
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * 作用域：默认变体
     */
    public function scopeDefault($query)
    {
        return $query->where('is_default', true);
    }

    /**
     * 作用域：有库存
     */
    public function scopeInStock($query)
    {
        return $query->where('stock_quantity', '>', 0);
    }

    /**
     * 作用域：按排序
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order');
    }
}
